package com.os.task;

import cn.hutool.core.date.DateUtil;
import com.os.model.DataNodeInfo;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.InetAddress;
import java.util.Date;

/**
 * @author 风亦未止
 * @date 2023/5/6 0:02
 */
@Log4j2
public class Heartbeat implements Runnable {

    private RabbitTemplate rabbitTemplate;
    private MessagePostProcessor messagePostProcessor;
    private String host;

    public Heartbeat(RabbitTemplate rabbitTemplate, MessagePostProcessor messagePostProcessor, String host) {
        this.rabbitTemplate = rabbitTemplate;
        this.messagePostProcessor = messagePostProcessor;
        this.host = host;
    }

    @SneakyThrows
    @Override
    public void run() {
        DataNodeInfo dataNodeInfo = new DataNodeInfo(host, DateUtil.now(), "data");
        while (true) {
            dataNodeInfo.setTime(DateUtil.now());
            rabbitTemplate.convertAndSend("api_exchange", "api_server", dataNodeInfo,messagePostProcessor);
            log.info(String.format("%s:发送心跳消息~", dataNodeInfo.getHost()));
            Thread.sleep(5000);
        }
    }
}
